import {
  Body,
  Controller,
  Del,
  Inject,
  Param,
  Post,
  Put,
  Query
} from '@midwayjs/core'
import { Context } from '@midwayjs/koa'
import {
  ApiBearerAuth,
  ApiOperation,
  ApiResponse,
  ApiTags
} from '@midwayjs/swagger'
import { Validate } from '@midwayjs/validate'
import { ExcelService } from '@ttou/midway-excel'

import { Permission } from '@/decorator'
import { DeleteDTO } from '@/dto'

import {
  CreateRoleDTO,
  FindAuthUserPageDTO,
  FindRolePageDTO,
  UpdateRoleDTO
} from './role.dto'
import { RoleExportSerialize } from './role.serialize'
import { RoleService } from './role.service'
import { GetRoleAuthPageVO, GetRolePageVO } from './role.vo'

@ApiBearerAuth()
@ApiTags('系统/角色接口')
@Controller('/system/role')
export class RoleController {
  @Inject()
  ctx: Context

  @Inject()
  roleService: RoleService

  @Inject()
  excelService: ExcelService

  @ApiOperation({ summary: '获取角色分页' })
  @ApiResponse({ status: 200, type: GetRolePageVO })
  @Permission('system:role:list')
  @Post('/page')
  @Validate()
  async getRolePage(@Body() dto: FindRolePageDTO) {
    return await this.roleService.handleFindPage(dto)
  }

  @ApiOperation({ summary: '新建角色' })
  @Permission('system:role:add')
  @Post('/create')
  @Validate()
  async createRole(@Body() dto: CreateRoleDTO) {
    await this.roleService.handleCreate(dto)
  }

  @ApiOperation({ summary: '更新角色' })
  @Permission('system:role:edit')
  @Put('/update/:id')
  @Validate()
  async updateRole(@Param('id') id: string, @Body() dto: UpdateRoleDTO) {
    await this.roleService.handleUpdate(id, dto)
  }

  @ApiOperation({ summary: '删除角色' })
  @Permission('system:role:remove')
  @Del('/delete')
  @Validate()
  async deleteRole(@Body() dto: DeleteDTO) {
    await this.roleService.handleDelete(dto)
  }

  @ApiOperation({ summary: '导出角色' })
  @Permission('system:role:export')
  @Post('/export')
  @Validate()
  async exportRolePage(@Body() dto: FindRolePageDTO) {
    const { list } = await this.roleService.handleFindPage(dto)

    const result = await this.excelService.handleExport({
      sheetName: '角色',
      filename: '角色报表',
      Cls: RoleExportSerialize,
      data: list
    })

    this.ctx.set(result.headers)
    this.ctx.body = result.body
  }

  @ApiOperation({ summary: '切换角色状态' })
  @Put('/toggleStatus/:id')
  async toggleRoleStatus(@Param('id') id: string) {
    await this.roleService.handleToggleStatus(id)
  }

  @ApiOperation({ summary: '获取角色权限分页' })
  @ApiResponse({ status: 200, type: GetRoleAuthPageVO })
  @Post('/roleAuth/page')
  @Validate()
  async getRoleAuthPage(
    @Query('id') id: string,
    @Body() dto: FindAuthUserPageDTO
  ) {
    return await this.roleService.handleFindAuthUserPage(id, dto)
  }

  @ApiOperation({ summary: '取消角色权限' })
  @Put('/roleAuth/cancelAuthUser')
  @Validate()
  async cancelAuthUser(@Query('id') id: string, @Body() dto: DeleteDTO) {
    await this.roleService.handleCancelAuthUser(id, dto)
  }
}
